package com.malty.apimanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.malty.apimanage.dao.UserInfoMapper;
import com.malty.apimanage.domain.dto.user.*;
import com.malty.apimanage.domain.vo.UserVO;
import com.malty.apimanage.service.UserInfoService;
import com.malty.common.ErrorCode;
import com.malty.common.domain.entity.UserInfo;
import com.malty.common.exception.BusinessException;
import com.malty.common.util.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.malty.apimanage.common.UserConstant.USER_LOGIN_STATE;

/**
 * @author Administrator
 * @description 针对表【user_info】的数据库操作Service实现
 * @createDate 2025-09-25 14:40:38
 */
@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {


    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "malty";

    @Override
    public long userRegister(UserRegisterReq userRegisterReq) {
        String password = userRegisterReq.getPassword();
        String account = userRegisterReq.getAccount();
        String checkPassword = userRegisterReq.getCheckPassword();

        if (!password.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }

        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());

        // 3. 分配 accessKey, secretKey
        String srcAccess = SALT + account + RandomUtils.nextInt(9999, 10000);
        String accessToken = DigestUtils.md5DigestAsHex(srcAccess.getBytes());
        String secretSrc = SALT + account + RandomUtils.nextInt(8000, 100000);
        String secretKey = DigestUtils.md5DigestAsHex(secretSrc.getBytes());

        // 4. 插入数据
        UserInfo user = new UserInfo(account, encryptPassword, accessToken, secretKey);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        return user.getId();
    }

    @Override
    public UserVO getLoginUser(HttpServletRequest request) {
        log.info("获取登录用户信息");
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        UserInfo currentUser = (UserInfo) userObj;
        log.info("session里面的用户信息:{}",toUserVo(currentUser));
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        log.info("用户信息:{}",toUserVo(currentUser));
        return toUserVo(currentUser);
    }

    @Override
    public UserInfo userLogin(UserLoginReq userLoginReq) {
        log.info("用户登录请求:{}", userLoginReq);

        String password = userLoginReq.getUserPassword();
        String account = userLoginReq.getUserAccount();

        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());

        // 查询用户是否存在
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account)
                .eq("password", encryptPassword);
        UserInfo user = this.getOne(queryWrapper);

        // 用户不存在
        if (user == null) {
            log.warn("user login failed, account cannot match password");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        log.info("登录完成信息:{}", user);
        return user;
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public UserInfo saveUser(UserAddReq userAddRequest) {
        UserInfo userInfo = toUserInfo(userAddRequest);
        this.save(userInfo);
        return userInfo;
    }

    @Override
    public UserVO getUserById(Long id) {
        UserInfo userInfo = this.getById(id);
        return toUserVo(userInfo);
    }

    @Override
    public List<UserVO> listUserByQuery(UserQueryReq userQueryReq) {
        UserInfo userQuery = new UserInfo();
        if (userQueryReq != null) {
            BeanUtils.copyProperties(userQueryReq, userQuery);
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(userQuery);
        List<UserInfo> userList = this.list(queryWrapper);
        return userList.stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
    }

    @Override
    public Page<UserVO> pageList(UserQueryReq userQueryReq) {
        long current = 1;
        long size = 10;
        UserInfo userQuery = new UserInfo();
        if (userQueryReq != null) {
            BeanUtils.copyProperties(userQueryReq, userQuery);
            current = userQueryReq.getCurrent();
            size = userQueryReq.getPageSize();
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(userQuery);
        Page<UserInfo> userPage = this.page(new Page<>(current, size), queryWrapper);

        Page<UserVO> userVOPage = new Page<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
        List<UserVO> userVOList = userPage.getRecords().stream()
                .map(user -> {
                    UserVO userVO = new UserVO();
                    BeanUtils.copyProperties(user, userVO);
                    return userVO;
                }).collect(Collectors.toList());
        userVOPage.setRecords(userVOList);
        return userVOPage;
    }

    @Override
    public boolean updateUserById(UserUpdateReq userUpdateRequest) {
        UserInfo user = new UserInfo();
        BeanUtils.copyProperties(userUpdateRequest, user);
        return this.updateById(user);
    }


    private UserVO toUserVo(UserInfo userInfo) {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userInfo, userVO);
        return userVO;
    }

    private UserInfo toUserInfo(UserAddReq userAddRequest) {
        return null;
    }

}




